/*
 * Copyright 2000-2005 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jetbrains.idea.accurev.accurev;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.process.InterruptibleActivity;
import com.jniwrapper.*;

import java.io.ByteArrayOutputStream;

/**
 * @author akireyev
 */
public class P4Callback extends Callback {
  private static final Logger LOG = Logger.getInstance("#org.jetbrains.idea.accurev.accurev.P4Callback");
  private PrimitiveArray myMessage = new PrimitiveArray(UInt8.class, 1);
  private Int myMessageSize = new Int();
  private ByteArrayOutputStream myText = new ByteArrayOutputStream();
  private ExternalArrayPointer myMessagePointer;
  private boolean myInactive = true;
  private InterruptibleActivity myExecutionWorker;

  public P4Callback() {
    myMessagePointer = new ExternalArrayPointer(myMessage);
    init(new Parameter[] {myMessageSize, myMessagePointer}, null);
    setCallingConvention(Function.CDECL_CALLING_CONVENTION);
  }

  public void callback() {
    try {
      int messageLen = (int)myMessageSize.getValue();
      myMessagePointer.readArray(messageLen);
      myText.write(myMessage.getBytes(), 0, messageLen);
      if (myInactive) {
        LOG.error("Message received while inactive: " + new String(myMessage.getBytes()));
      }
    }
    finally {
      if (myExecutionWorker != null) myExecutionWorker.touch();
    }
  }

  public String getText() {
    return new String(myText.toByteArray());
  }

  public void reset() {
    if (myText.size() > 0) {
      LOG.error("Perforce callback received inactive messages: " + myText);
    }
    myText = new ByteArrayOutputStream();
    myInactive = false;
    myExecutionWorker = null;
  }

  public void deactivate() {
    myText = new ByteArrayOutputStream();
    myInactive = true;
    myExecutionWorker = null;
  }

  public void setExecutionWorker(final InterruptibleActivity worker) {
    myExecutionWorker = worker;
  }

  public boolean isActive() {
    return !myInactive;
  }

  public byte[] getBytes() {
    return myText.toByteArray();
  }
}
